class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

import collections
class Solution(object):
    def kthSmallest(self, root, k):
        """
        :type root: TreeNode
        :type k: int
        :rtype: int
        """
        stack = collections.deque([root])
        while stack[-1].left:
            stack.append(stack[-1].left)
        index = 0
        while True:
            node = stack.pop()
            index += 1
            if index == k:
                return node.val
            if node.right:
                node = node.right
                while node:
                    stack.append(node)
                    node = node.left

